# -*- coding: utf-8 -*-

import os
import logging
from logging import handlers

class Logger(object):

    # 日志级别关系映射
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }
    
    def __init__(self, filename, level='info', when='D', backCount=7, fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):

        # 创建文件夹
        logDir = os.path.dirname(filename)
        if logDir != '':
            os.makedirs(logDir, 0o664, True)

        logger = logging.getLogger(filename)

        # 设置日志格式
        format_str = logging.Formatter(fmt)

        # 设置日志级别
        logger.setLevel(self.level_relations.get(level))

        # 屏幕输出
        sh = logging.StreamHandler()
        sh.setFormatter(format_str)
        logger.addHandler(sh)

        # 文件输出
        th = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backCount, encoding='utf-8')
        th.setFormatter(format_str)
        logger.addHandler(th)

        self.logger = logger
    
    def __getattr__(self, *args, **kwargs):
        return getattr(self.logger, args[0])

